package com.game.config.interceptor;

import com.game.comment.exection.ServiceException;
import com.game.comment.util.JwtUtils;
import com.game.comment.util.ReqUtil;
import com.jthinking.common.util.ip.IPInfo;
import com.jthinking.common.util.ip.IPInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReqInterceptor implements HandlerInterceptor {
    @Resource
    private ValueOperations<Object, Object> valueOperations;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        String clientIp = ReqUtil.getClientIp(request);
        IPInfo ipInfo = IPInfoUtils.getIpInfo(clientIp);
        if (ipInfo.isOverseas()){
            throw new ServiceException("不允许访问海外IP");
        }
        // 请求头
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            log.error(">>>>>请求地址>>>>>{}",request.getRequestURI());
            throw new ServiceException("请登录");
        }
        if (!JwtUtils.verify(token)){
            throw new ServiceException("非法token");
        }
        Long uid = JwtUtils.getPlayerId(token);
        Object o = valueOperations.get("player:" + uid+ ":loginKey");
        if (!Objects.equals(o, token)){
            throw new ServiceException("登录令牌不匹配,请重新登录");
        }
        // 续期
        valueOperations.set("player:" + uid+ ":loginKey", token, 2, TimeUnit.HOURS);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
        // if(response.getStatus()==500){
        //     modelAndView.setViewName("/errorpage/500");
        // }else if(response.getStatus()==404){
        //     modelAndView.setViewName("/errorpage/404");
        // }
    }

    /**
     * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后，也就是DispatcherServlet渲染了视图执行，
     * 这个方法的主要作用是用于清理资源的，当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
